package com.cupk.controllers;

import com.cupk.dtos.*;
import com.cupk.security.JwtTokenProvider;
import com.cupk.services.AuthService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthController {

    private final AuthService authService;
    private final AuthenticationManager authenticationManager;
    private final JwtTokenProvider tokenProvider;
    // **【核心修改 1】**: 移除了对 UserMapper 的直接注入
    // private final UserMapper userMapper;

    /**
     * 发送【注册】验证码
     */
    @PostMapping("/send-registration-code")
    public ResponseEntity<MessageResponse> sendRegistrationCode(@RequestBody Map<String, String> payload) {
        String email = payload.get("email");
        if (email == null || email.isEmpty()) {
            return ResponseEntity.badRequest().body(new MessageResponse("邮箱地址不能为空。"));
        }
        authService.sendRegistrationCode(email);
        return ResponseEntity.ok(new MessageResponse("验证码已成功发送，请检查您的邮箱。"));
    }

    /**
     * 发送【密码重置】验证码
     */
    @PostMapping("/forgot-password/send-code")
    public ResponseEntity<MessageResponse> sendPasswordResetCode(@RequestBody Map<String, String> payload) {
        String email = payload.get("email");
        if (email == null || email.isEmpty()) {
            return ResponseEntity.badRequest().body(new MessageResponse("邮箱地址不能为空。"));
        }
        authService.sendPasswordResetCode(email);
        return ResponseEntity.ok(new MessageResponse("如果该邮箱已注册，您将会收到一封验证码邮件。"));
    }

    /**
     * 重置密码
     */
    @PostMapping("/forgot-password/reset")
    public ResponseEntity<MessageResponse> resetPassword(@Valid @RequestBody ResetPasswordRequest request) {
        authService.resetPassword(request);
        return ResponseEntity.ok(new MessageResponse("密码已成功重置！"));
    }

    @PostMapping("/register")
    public ResponseEntity<MessageResponse> registerUser(@Valid @RequestBody RegisterRequest registerRequest) {
        String requestedRole = registerRequest.getRole();
        if ("ADMIN".equalsIgnoreCase(requestedRole)) {
            registerRequest.setRole("ADMIN");
        } else {
            registerRequest.setRole("RESEARCHER");
        }
        authService.registerUser(registerRequest);
        return ResponseEntity.ok(new MessageResponse("用户注册成功!"));
    }

    @PostMapping("/login")
    public ResponseEntity<JwtResponse> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
        // 1. Spring Security 的认证流程
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));

        SecurityContextHolder.getContext().setAuthentication(authentication);

        // 2. 生成 JWT
        String jwt = tokenProvider.generateToken(authentication);

        // 3. **【核心修改 2】**: 调用 Service 层来获取完整的用户信息和构建响应
        JwtResponse jwtResponse = authService.buildLoginResponse(authentication.getName(), jwt);

        return ResponseEntity.ok(jwtResponse);
    }
}